package com.goldsprite.infinityworld.screens.examples.ui;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.goldsprite.gdxcore.screens.GScreen;

/**
 * 搞懂了如何转换坐标系绘制: 通过调整camera的大小宽高并将合并矩阵应用到batch的投影矩阵即可, (之前错误的想法是通过转换视口, 这是错误的)
 */
public class ViewportCoordExampleScreen extends GScreen {
	private SpriteBatch batch;
	private Texture avatar;
	private FitViewport viewport;
	private OrthographicCamera cam;
	private float worldWidth = 100, worldHeight = 100; // 逻辑宽高

	@Override
	public void create() {
		avatar = new Texture("shikeik_avatar.png");
		batch = new SpriteBatch();

		cam = new OrthographicCamera();
		viewport = new FitViewport(960, 540, cam);
		viewport.apply(true);
	}

	@Override
	public void render(float delta) {
		// 清屏
		ScreenUtils.clear(0.35f, 0.35f, 0.35f, 1);

		batch.begin();
		{//绘制于左下1/2大小图片
			updateCamera(cam);
			batch.setProjectionMatrix(cam.combined);
			batch.draw(avatar, 0, 0, cam.viewportWidth/2, cam.viewportHeight/2);
		}
		{//绘制于右下1/4大小图片
			updateCamera(cam, -(200-50), 0, 200, 200);
			batch.setProjectionMatrix(cam.combined);
			batch.draw(avatar, 0, 0, cam.viewportWidth/4, cam.viewportHeight/4);
		}
		batch.end();
	}

	private void updateCamera(OrthographicCamera cam) {
		updateCamera(cam, 0, 0, viewport.getWorldWidth(), viewport.getWorldHeight());
	}
	private void updateCamera(OrthographicCamera cam, float camX, float camY, float width, float height) {
		cam.viewportWidth = width;
		cam.viewportHeight = height;
		cam.position.set(camX+width/2, camY+height/2, 0);
		cam.update();
	}
}
